const path = require('path')

const multer = require('@koa/multer')
const Jimp = require('jimp')

const { LARGE_TYPE, MIDDLE_TYPE, SMALL_TYPE } = require('../constants/picture-type')

const { AVATAR_PATH, PICTURE_PATH } = require('../constants/file-path')

const avatarUpload = multer({
  dest: AVATAR_PATH
})

const pictureUpload = multer({
  dest: PICTURE_PATH
})

const avatarHandler = avatarUpload.single('avatar')

const pictureHandler = pictureUpload.array('picture', 9)

// 对图片尺寸进行裁剪(small/middle/large/原图)
const pictureResize = async (ctx, next) => {
  const files = ctx.request.files
  console.log('files:---', files)

  for(let file of files) {
    // const destPath = path.join(file.destination, file.filename)
    // console.log('destPath: ---', destPath);

    // 这里选择使用异步的处理方式，因为我们不希望等图片被处理完之后才进入下一个中间件，从而提升响应速度
    Jimp.read(file.path).then(image => {
      // image.resize(<width>, <length>)
      image.resize(1280, Jimp.AUTO).write(`${file.path}-${LARGE_TYPE}`)
      image.resize(640, Jimp.AUTO).write(`${file.path}-${MIDDLE_TYPE}`)
      image.resize(320, Jimp.AUTO).write(`${file.path}-${SMALL_TYPE}`)
    })  
  }

  await next()
}


module.exports = {
  avatarHandler,
  pictureHandler,
  pictureResize
}